//
//  PlatformFactory.swift
//  MySpriteKit
//
//  Created by haogaoming on 16/9/9.
//  Copyright © 2016年 郝高明. All rights reserved.
//  平台工厂类

import SpriteKit

/**
 *  协议
 */
protocol ProtocolMainScene:NSObjectProtocol {
    func onGetData(dist:CGFloat)
}

class PlatformFactory: SKNode {
    let textureLeft = SKTexture(imageNamed: "platform_l")
    let textureMid = SKTexture(imageNamed: "platform_m")
    let textureRight = SKTexture(imageNamed: "platform_r")
    
    //存放产生的平台
    var platformsArray = [Platform]()
    //接受主场景的长度
    var sceneWidth:CGFloat = 0.0
    
    weak var delegate:ProtocolMainScene?
    /**
     创建随机的平台长度
     */
    func createPlatormRandom() {
        //中间块数
        let midNum:CGFloat = CGFloat(arc4random()%4+1)
        //时间间隔
        let gap:CGFloat = CGFloat(arc4random()%8+1)
        //x坐标
        let x:CGFloat = self.sceneWidth + midNum*50 + gap + 100
        //y坐标
        let y:CGFloat = CGFloat(arc4random()%200+200)
        
        createPlatorm(Int(midNum), x: x, y: y)
    }
    /**
     创建平台
     
     - parameter midNum: 中间有几个模块
     - parameter x:      x坐标
     - parameter y:      y坐标
     */
    func createPlatorm(midNum:Int,x:CGFloat,y:CGFloat) {
        let platform = Platform()
        
        //平台左边部分
        let platform_left = SKSpriteNode(texture: textureLeft)
        platform_left.anchorPoint = CGPointMake(0, 0.9)
        
        //平台右边部分
        let platform_right = SKSpriteNode(texture: textureRight)
        platform_right.anchorPoint = CGPointMake(0, 0.9)
        
        //存储中间部门的数组
        var arrPlatform = [SKSpriteNode]()
        
        arrPlatform.append(platform_left)
        platform.position = CGPointMake(x, y)
        
        for _ in 1...midNum {
            //平台的中间部分
            let platform_mid = SKSpriteNode(texture: textureMid)
            platform_mid.anchorPoint = CGPointMake(0, 0.9)
            arrPlatform.append(platform_mid)
        }

        arrPlatform.append(platform_right)
        
        platform.onCreate(arrPlatform)
        
        addChild(platform)
        
        platformsArray.append(platform)
        
        //通用公式：平台的长度+外部左边X-主场景的宽度
        delegate?.onGetData(platform.width + x - sceneWidth)
    }
    /**
     平台移动方法
     
     - parameter speed: 移动的距离
     */
    func platformMove(speed:CGFloat) {
        //遍历平台，把平台的x减计算
        for platform in platformsArray {
            platform.position.x -= speed
        }
        //当第一个平台的x小于-平台的宽，则移除
        if platformsArray[0].position.x < -platformsArray[0].width{
            platformsArray[0].removeFromParent()
            platformsArray.removeAtIndex(0)
        }
    }
}
